#!/usr/bin/env python3
"""
快速分析Java插件与Go服务通信
"""

import subprocess
import os
import zipfile

def extract_and_search():
    """提取并搜索关键信息"""
    jar_file = "lingma-jetbrains/lib/cosy-intellij-2.5.16.jar"
    
    if not os.path.exists("temp_jar"):
        os.makedirs("temp_jar")
        
        print("提取JAR文件...")
        with zipfile.ZipFile(jar_file, 'r') as zip_ref:
            zip_ref.extractall("temp_jar")
    
    print("\n🔍 搜索通信相关信息...")
    
    # 搜索关键字符串
    keywords = [
        "localhost", "127.0.0.1", "port", "socket", "websocket",
        "ProcessBuilder", "exec", "Lingma", "lsp", "jsonrpc"
    ]
    
    findings = {}
    
    # 搜索字符串资源
    for root, dirs, files in os.walk("temp_jar"):
        for file in files:
            if file.endswith(('.properties', '.json', '.xml', '.txt')):
                filepath = os.path.join(root, file)
                try:
                    with open(filepath, 'r', encoding='utf-8', errors='ignore') as f:
                        content = f.read()
                        
                        for keyword in keywords:
                            if keyword in content:
                                if keyword not in findings:
                                    findings[keyword] = []
                                
                                # 提取包含关键词的行
                                lines = content.split('\n')
                                for i, line in enumerate(lines):
                                    if keyword in line:
                                        findings[keyword].append(f"{filepath}:{i+1}: {line.strip()}")
                except:
                    pass
    
    # 输出发现
    for keyword, results in findings.items():
        print(f"\n🔑 关键词: {keyword}")
        for result in results[:5]:  # 只显示前5个
            print(f"  {result}")
    
    return findings

def search_specific_classes():
    """搜索特定的类文件内容"""
    print("\n🎯 搜索特定类...")
    
    # 使用strings命令搜索二进制中的字符串
    jar_file = "lingma-jetbrains/lib/cosy-intellij-2.5.16.jar"
    
    try:
        result = subprocess.run(['strings', jar_file], capture_output=True, text=True)
        content = result.stdout
        
        # 搜索关键模式
        patterns = {
            "端口": [line for line in content.split('\n') if any(p in line for p in ['localhost', '127.0.0.1', 'port']) and line.strip()],
            "进程": [line for line in content.split('\n') if any(p in line for p in ['ProcessBuilder', 'exec', 'Lingma']) and line.strip()],
            "协议": [line for line in content.split('\n') if any(p in line for p in ['lsp', 'jsonrpc', 'websocket']) and line.strip()],
            "URL": [line for line in content.split('\n') if ('http' in line or 'ws://' in line) and line.strip()]
        }
        
        for category, lines in patterns.items():
            if lines:
                print(f"\n📋 {category}相关:")
                for line in lines[:10]:  # 只显示前10个
                    print(f"  {line}")
    
    except Exception as e:
        print(f"strings命令失败: {e}")

def find_lsp_config():
    """查找LSP配置"""
    print("\n🔧 查找LSP配置...")
    
    # 搜索LSP相关的类和配置
    if os.path.exists("temp_jar"):
        for root, dirs, files in os.walk("temp_jar"):
            for file in files:
                if 'lsp' in file.lower() or 'language' in file.lower():
                    filepath = os.path.join(root, file)
                    print(f"发现LSP相关文件: {filepath}")
                    
                    if file.endswith('.class'):
                        # 尝试用javap分析
                        try:
                            class_name = filepath.replace('temp_jar/', '').replace('.class', '').replace('/', '.')
                            result = subprocess.run([
                                'javap', '-cp', 'temp_jar', '-c', class_name
                            ], capture_output=True, text=True, timeout=10)
                            
                            if result.returncode == 0:
                                output = result.stdout
                                # 查找常量
                                for line in output.split('\n'):
                                    if any(keyword in line for keyword in ['localhost', 'port', 'socket', 'ldc']):
                                        print(f"  {line.strip()}")
                        except:
                            pass

def analyze_manifest():
    """分析MANIFEST文件"""
    print("\n📋 分析MANIFEST...")
    
    manifest_path = "temp_jar/META-INF/MANIFEST.MF"
    if os.path.exists(manifest_path):
        with open(manifest_path, 'r') as f:
            content = f.read()
            print(content)

def search_connection_strings():
    """搜索连接字符串"""
    print("\n🔗 搜索连接字符串...")
    
    jar_file = "lingma-jetbrains/lib/cosy-intellij-2.5.16.jar"
    
    # 使用grep搜索特定模式
    patterns = [
        "127.0.0.1",
        "localhost",
        "ws://",
        "wss://",
        ":([0-9]+)",  # 端口模式
        "socket",
        "connect",
        "ProcessBuilder"
    ]
    
    for pattern in patterns:
        try:
            result = subprocess.run([
                'zgrep', '-a', pattern, jar_file
            ], capture_output=True, text=True)
            
            if result.stdout:
                print(f"\n模式 '{pattern}':")
                lines = result.stdout.split('\n')
                for line in lines[:5]:  # 只显示前5行
                    if line.strip():
                        print(f"  {line}")
        except:
            pass

def main():
    print("=" * 60)
    print("快速Java插件通信分析")
    print("=" * 60)
    
    # 1. 提取并搜索文本
    findings = extract_and_search()
    
    # 2. 搜索特定类
    search_specific_classes()
    
    # 3. 查找LSP配置
    find_lsp_config()
    
    # 4. 分析MANIFEST
    analyze_manifest()
    
    # 5. 搜索连接字符串
    search_connection_strings()
    
    print("\n" + "=" * 60)
    print("分析完成")
    print("=" * 60)

if __name__ == "__main__":
    main()